package servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import biz.FoodBiz;
import biz.FoodTypeBiz;
import biz.RateBiz;
import biz.impl.FoodBizImpl;
import biz.impl.FoodTypeBizImpl;
import biz.impl.RateBizImpl;
import entity.Food;
import entity.FoodType;
import entity.Rate;


@WebServlet("/FoodList.html")
public class FoodListServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
 
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		FoodTypeBiz ftb = new FoodTypeBizImpl();
		List<FoodType> foodTypeList = ftb.queryAllFoodType();
		
		String Sftid = request.getParameter("ftid");//食物类型Id
		String currentPageStr = request.getParameter("currentPage");
		int currentPage=1;//当前页面的页码
		if(currentPageStr!=null&&!currentPageStr.isEmpty()){
			currentPage=Integer.valueOf(currentPageStr);
		}
		FoodBiz fb= new FoodBizImpl();

		List<Food> allFood = fb.queryAllFood();//全部食物
		int pageSize=6;
//		分页
		if(Sftid!=null&&!Sftid.isEmpty()){//有类别Id
			List<Food> typeList = new ArrayList<Food>();
			int ftid = Integer.valueOf(Sftid);
			for (Food food : allFood) {
				if(food.getFoodType().getFtId()==ftid){
					typeList.add(food);
				}
			}
			int totalPageNum=typeList.size()%pageSize==0?typeList.size()/pageSize:typeList.size()/pageSize+1;
			List<Food> foodList = fb.queryFood(typeList, currentPage, pageSize);
			request.setAttribute("foodList", foodList);
			request.setAttribute("pageNum", totalPageNum);
		}else{//全部显示
			
			Integer totalCount = fb.queryAllFoodTotalCount();
			int totalPageNum=totalCount%pageSize==0?totalCount/pageSize:totalCount/pageSize+1;
			//分页显示
			List<Food> foodList = fb.queryFood(allFood, currentPage, pageSize);
			
			request.setAttribute("foodList", foodList);
			request.setAttribute("pageNum", totalPageNum);
		}
		
		
		
		
		RateBiz rb =new RateBizImpl();
		List<Rate> ratelist = rb.queryAllRate();
		request.setAttribute("ratelist", ratelist);
		request.setAttribute("foodTypeList", foodTypeList);
		request.getRequestDispatcher("/foodlist.jsp").forward(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
